def is_point_in(x, y, points):
    count = 0
    x1, y1 = points[0]
    x1_part = (y1 > y) or ((x1 - x > 0) and (y1 == y))
    x2, y2 = '', ''  # points[1]
    points.append((x1, y1))
    for point in points[1:]:
        x2, y2 = point
        x2_part = (y2 > y) or ((x2 > x) and (y2 == y))
        if x2_part == x1_part:
            x1, y1 = x2, y2
            continue
        mul = (x1 - x)*(y2 - y) - (x2 - x)*(y1 - y)
        if mul > 0:
            count += 1
        elif mul < 0:
            count -= 1
        x1, y1 = x2, y2
        x1_part = x2_part
    if count == 2 or count == -2:
        return True
    else:
        return False

import dicom

ct = dicom.read_file("CT.1.2.392.200036.9116.2.5.1.37.2424156666.1405581882.727467.dcm")
originX = float(ct[0x0020, 0x0032].value[0])
originY = float(ct[0x0020, 0x0032].value[1])
spacingX = float(ct[0x0028, 0x0030].value[0])
spacingY = float(ct[0x0028, 0x0030].value[1])
col = ct[0x0028, 0x0011].value
row = ct[0x0028, 0x0010].value
centerX = originX + spacingX * col / 2
centerY = originY + spacingY * row / 2
print (centerX, centerY)

ds = dicom.read_file("RS.1.2.246.352.71.4.1245719819.1942.20140723142410.dcm")

StructureSetSq = ds[0x3006, 0x0020].value
for item in StructureSetSq:
    RoiName = item[0x3006, 0x0026].value
    if RoiName == "BODY":
        RoiNumber = item[0x3006, 0x0022].value
        
bodyCountours = []
        
RoiCountourSq = ds[0x3006, 0x0039].value
for item in RoiCountourSq: 
    if item[0x3006, 0x0084].value == RoiNumber:
        CountourSq = item[0x3006, 0x0040].value
#        file.write(str(len(CountourSq)))
#        file.write(' ')
        for countour in CountourSq:
#            file.write(str(countour[0x3006, 0x0046].value))
#            file.write(' ')
            arr = []
            pts = []
            for i in range(0,len(countour[0x3006, 0x0050].value)/3):
#                file.write(str(v))
#                file.write(' ')
                arr.append([countour[0x3006, 0x0050].value[3*i], countour[0x3006, 0x0050].value[3*i+1]])
                pts.append([countour[0x3006, 0x0050].value[3*i], countour[0x3006, 0x0050].value[3*i+1], countour[0x3006, 0x0050].value[3*i+2]])
            if is_point_in(centerX, centerY, arr):
                bodyCountours.append(pts)
            else:
                print ("bad countour")
                
file = open("bodyCountour.xyz", "w")
file.write(str(len(bodyCountours)))
file.write(' ')
for countour in bodyCountours:
    file.write(str(len(countour)))
    file.write(' ')
    for pt in countour:
        file.write(str(pt[0]))
        file.write(' ')
        file.write(str(pt[1]))
        file.write(' ')
        file.write(str(pt[2]))
        file.write(' ')
file.close()
